package com.nwpu.controller;

import com.nwpu.common.ErrorEnum;
import com.nwpu.common.Result;
import com.nwpu.domain.User;
import com.nwpu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author DPH
 * @date 2023/5/21
 */
@RestController
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping
    public Result<String> register(@RequestBody @Valid User user, BindingResult errors) {
        if (errors.hasErrors()) {
            return Result.of(null, errors.getFieldError().getDefaultMessage());
        }
        User user1 = userService.getUserById(user.getUserId());
        if (user1 != null) {
            return Result.error(ErrorEnum.DUPLICATE_KEY);
        }
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));

        boolean res = userService.saveUser(user);
        if (res) {
            return Result.of("注册成功");
        } else {
            return Result.error(ErrorEnum.INTERNAL_SERVER_ERROR);
        }
    }
}
